package cn.damai.mine.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableResultDemo {
	
	public static void main(String[] args) {
		
//		ExecutorService executorService = Executors.newFixedThreadPool(5);
		ExecutorService executorService = Executors.newCachedThreadPool();
		
		CountDownLatch latch = new CountDownLatch(5);
		
		List<Future<String>> list = new ArrayList<Future<String>>();
		for (int i = 0; i < 5; i++) {
			Future<String>  future = executorService.submit(new TaskWithResult(i,latch));
			list.add(future);
		}
		
		try {
			latch.await();
			System.out.println("------------all of the tasks has been finished!-----------");
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		for (Future<String> future : list) {
			
			try {
				System.out.println(future.get());
			} catch (InterruptedException | ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				executorService.shutdown();
			}
		}
		
	}
	
}

class TaskWithResult implements Callable<String> {
	
	private int taskId;
	private CountDownLatch latch;
	
	public TaskWithResult(int taskId,CountDownLatch latch){
		this.taskId = taskId;
		this.latch  = latch;
	}
	
	@Override
	public String call() throws Exception {
		// TODO Auto-generated method stub
		
		System.out.println(Thread.currentThread().getName() + " �߳��Զ�����call�������ɻ����");
		latch.countDown();
		return Thread.currentThread().getName() + " �߳��Զ���������"+taskId+"��call������"; 
	}
	
}
